#include <string.h>
#include <raw_api.h>
#include <mm/pool/raw_memp.h>
#include <raw_debug.h>

#define LWIP_MEMPOOL(name,num,size,desc) LWIP_MEMPOOL_DECLARE(name,num,size,desc)
#include "memp_std.h"

const struct memp_desc* const memp_pools[MEMP_MAX] = {
#define LWIP_MEMPOOL(name,num,size,desc) &memp_ ## name,
#include "memp_std.h"
};



/* Get the number of entries in an array ('x' must NOT be a pointer!) */
#define LWIP_ARRAYSIZE(x) (sizeof(x)/sizeof((x)[0]))

static RAW_MUTEX  memp_mutex_lock;

#if MEMP_SANITY_CHECK
/**
 * Check that memp-lists don't form a circle, using "Floyd's cycle-finding algorithm".
 */
static int
memp_sanity(const struct memp_desc *desc)
{
  struct memp *t, *h;

  t = *desc->tab;
  if (t != 0) {
    for (h = t->next; (t != 0) && (h != 0); t = t->next,
      h = ((h->next != 0) ? h->next->next : 0)) {
      if (t == h) {
        return 0;
      }
    }
  }

  return 1;
}
#endif /* MEMP_SANITY_CHECK*/

#if MEMP_OVERFLOW_CHECK

/**
 * Check if a memp element was victim of an overflow
 * (e.g. the restricted area after it has been altered)
 *
 * @param p the memp element to check
 * @param memp_type the pool p comes from
 */
static void
memp_overflow_check_element_overflow(struct memp *p, const struct memp_desc *desc)
{
  RAW_U16 k;
  RAW_U8 *m;
#if MEMP_SANITY_REGION_AFTER_ALIGNED > 0
  m = (RAW_U8*)p + MEMP_SIZE + desc->size;
  for (k = 0; k < MEMP_SANITY_REGION_AFTER_ALIGNED; k++) {
    if (m[k] != 0xcd) {
      char errstr[128] = "detected memp overflow in pool ";
      strcat(errstr, desc->desc);
      RAW_MESSAGE_ASSERT(errstr, 0);
    }
  }
#endif
}

/**
 * Check if a memp element was victim of an underflow
 * (e.g. the restricted area before it has been altered)
 *
 * @param p the memp element to check
 * @param memp_type the pool p comes from
 */
static void
memp_overflow_check_element_underflow(struct memp *p, const struct memp_desc *desc)
{
  RAW_U16 k;
  RAW_U8 *m;
#if MEMP_SANITY_REGION_BEFORE_ALIGNED > 0
  m = (RAW_U8*)p + MEMP_SIZE - MEMP_SANITY_REGION_BEFORE_ALIGNED;
  for (k = 0; k < MEMP_SANITY_REGION_BEFORE_ALIGNED; k++) {
    if (m[k] != 0xcd) {
      char errstr[128] = "detected memp underflow in pool ";
      strcat(errstr, desc->desc);
      RAW_MESSAGE_ASSERT(errstr, 0);
    }
  }
#endif
}

/**
 * Do an overflow check for all elements in every pool.
 *
 * @see memp_overflow_check_element for a description of the check
 */
static void
memp_overflow_check_all(void)
{
  RAW_U16 i, j;
  struct memp *p;

  for (i = 0; i < MEMP_MAX; ++i) {
    p = (struct memp *)(RAW_PROCESSOR_UINT)(memp_pools[i]->base);
    for (j = 0; j < memp_pools[i]->num; ++j) {
      memp_overflow_check_element_overflow(p, memp_pools[i]);
      memp_overflow_check_element_underflow(p, memp_pools[i]);
      p = (struct memp*)(RAW_PROCESSOR_UINT)((RAW_U8*)p + MEMP_SIZE + memp_pools[i]->size + MEMP_SANITY_REGION_AFTER_ALIGNED);
    }
  }
}

/**
 * Initialize the restricted areas of all memp elements in every pool.
 */
static void
memp_overflow_init(const struct memp_desc *desc)
{
  RAW_U16 i;
  struct memp *p;
  RAW_U8 *m;

  p = (struct memp *)(RAW_PROCESSOR_UINT)(desc->base);
  for (i = 0; i < desc->num; ++i) {
#if MEMP_SANITY_REGION_BEFORE_ALIGNED > 0
    m = (RAW_U8*)p + MEMP_SIZE - MEMP_SANITY_REGION_BEFORE_ALIGNED;
    raw_memset(m, 0xcd, MEMP_SANITY_REGION_BEFORE_ALIGNED);
#endif
#if MEMP_SANITY_REGION_AFTER_ALIGNED > 0
    m = (RAW_U8*)p + MEMP_SIZE + desc->size;
    raw_memset(m, 0xcd, MEMP_SANITY_REGION_AFTER_ALIGNED);
#endif
    p = (struct memp*)(RAW_PROCESSOR_UINT)((RAW_U8*)p + MEMP_SIZE + desc->size + MEMP_SANITY_REGION_AFTER_ALIGNED);
  }
}
#endif /* MEMP_OVERFLOW_CHECK */


void
memp_init_pool(const struct memp_desc *desc)
{
  int i;
  struct memp *memp;
  
  *desc->tab = 0;
  memp = (struct memp*)LWIP_MEM_ALIGN(desc->base);
  /* create a linked list of memp elements */
  for (i = 0; i < desc->num; ++i) {
    memp->next = *desc->tab;
    *desc->tab = memp;
   /* cast through void* to get rid of alignment warnings */
   memp = (struct memp *)(void *)((RAW_U8 *)memp + MEMP_SIZE + desc->size
#if MEMP_OVERFLOW_CHECK
      + MEMP_SANITY_REGION_AFTER_ALIGNED
#endif
    );
  }  

#if MEMP_OVERFLOW_CHECK
  memp_overflow_init(desc);
#endif /* MEMP_OVERFLOW_CHECK */

#if MEMP_STATS
  desc->stats->avail = desc->num;

#if defined(LWIP_DEBUG) || LWIP_STATS_DISPLAY
  desc->stats->name  = desc->desc;
#endif /* defined(LWIP_DEBUG) || LWIP_STATS_DISPLAY */
#endif /* MEMP_STATS */
}

/**
 * Initialize this module.
 *
 * Carves out memp_memory into linked lists for each pool-type.
 */
void
memp_init(void)
{
  RAW_U16 i;

  
  raw_mutex_create(&memp_mutex_lock, (RAW_U8 *)"memp_mutex_lock", RAW_MUTEX_INHERIT_POLICY, 0);
  
  /* for every pool: */
  for (i = 0; i < LWIP_ARRAYSIZE(memp_pools); i++) {
    memp_init_pool(memp_pools[i]);

#if LWIP_STATS
    lwip_stats.memp[i] = memp_pools[i]->stats;
#endif
  }

#if MEMP_OVERFLOW_CHECK
  /* check everything a first time to see if it worked */
  memp_overflow_check_all();
#endif /* MEMP_OVERFLOW_CHECK */
}

void *
#if !MEMP_OVERFLOW_CHECK
memp_malloc_pool(const struct memp_desc *desc)
#else
memp_malloc_pool_fn(const struct memp_desc *desc, const char* file, const int line)
#endif
{
  struct memp *memp;
 
  memp = *desc->tab;

  if (memp != 0) {

#if MEMP_OVERFLOW_CHECK == 1
	memp_overflow_check_element_overflow(memp, desc);
	memp_overflow_check_element_underflow(memp, desc);
#endif /* MEMP_OVERFLOW_CHECK */

    *desc->tab = memp->next;
#if MEMP_OVERFLOW_CHECK
    memp->next = 0;
    memp->file = file;
    memp->line = line;
#endif /* MEMP_OVERFLOW_CHECK */

    RAW_MESSAGE_ASSERT("memp_malloc: memp properly aligned",
                ((RAW_PROCESSOR_UINT)memp % MEM_ALIGNMENT) == 0);
    /* cast through void* to get rid of alignment warnings */
    memp = (struct memp*)(void *)((RAW_U8*)memp + MEMP_SIZE);
  }

  if (memp != 0) {
#if MEMP_STATS
    desc->stats->used++;
    if (desc->stats->used > desc->stats->max) {
      desc->stats->max = desc->stats->used;
    }
#endif
  } else {
    RAW_DEBUGF(RAW_DBG_ON | RAW_DBG_LEVEL_SERIOUS, ("memp_malloc: out of memory in pool %s\n", desc->desc));
#if MEMP_STATS
    desc->stats->err++;
#endif
  }

  return memp;
}

/**
 * Get an element from a specific pool.
 *
 * @param type the pool to get an element from
 *
 * the debug version has two more parameters:
 * @param file file name calling this function
 * @param line number of line where this function is called
 *
 * @return a pointer to the allocated memory or a 0 pointer on error
 */
void *
#if !MEMP_OVERFLOW_CHECK
memp_malloc(memp_t type)
#else
memp_malloc_fn(memp_t type, const char* file, const int line)
#endif
{
  void *memp;
  RAW_OS_ERROR ret;
  
  ret = raw_mutex_get(&memp_mutex_lock, RAW_WAIT_FOREVER);
  RAW_ASSERT(ret == RAW_SUCCESS);

  RAW_ERROR("memp_malloc: type < MEMP_MAX", (type < MEMP_MAX), return 0;);


#if MEMP_OVERFLOW_CHECK >= 2
  memp_overflow_check_all();
#endif /* MEMP_OVERFLOW_CHECK >= 2 */

#if !MEMP_OVERFLOW_CHECK
  memp = memp_malloc_pool(memp_pools[type]);
#else
  memp = memp_malloc_pool_fn(memp_pools[type], file, line);
#endif

  ret = raw_mutex_put(&memp_mutex_lock);
  RAW_ASSERT(ret == RAW_SUCCESS);

  return memp;
}

static void
#ifdef LWIP_HOOK_MEMP_AVAILABLE
do_memp_free_pool(const struct memp_desc* desc, void *mem, struct memp **old_first)
#else
do_memp_free_pool(const struct memp_desc* desc, void *mem)
#endif
{
  struct memp *memp;
  
  
  RAW_MESSAGE_ASSERT("memp_free: mem properly aligned",
                ((RAW_PROCESSOR_UINT)mem % MEM_ALIGNMENT) == 0);

 

  /* cast through void* to get rid of alignment warnings */
  memp = (struct memp *)(void *)((RAW_U8*)mem - MEMP_SIZE);

#if MEMP_OVERFLOW_CHECK == 1
  memp_overflow_check_element_overflow(memp, desc);
  memp_overflow_check_element_underflow(memp, desc);
#endif /* MEMP_OVERFLOW_CHECK */

#if MEMP_STATS
  desc->stats->used--;
#endif

  memp->next = *desc->tab;

#ifdef LWIP_HOOK_MEMP_AVAILABLE
  if (old_first)
    *old_first = *desc->tab;
#endif

  *desc->tab = memp;

#if MEMP_SANITY_CHECK
  RAW_MESSAGE_ASSERT("memp sanity", memp_sanity(desc));
#endif /* MEMP_SANITY_CHECK */
  
}

void
memp_free_pool(const struct memp_desc* desc, void *mem)
{
  if ((desc == 0) || (mem == 0)) {
    return;
  }

#ifdef LWIP_HOOK_MEMP_AVAILABLE
  do_memp_free_pool(desc, mem, 0);
#else
  do_memp_free_pool(desc, mem);
#endif
}

/**
 * Put an element back into its pool.
 *
 * @param type the pool where to put mem
 * @param mem the memp element to free
 */
void
memp_free(memp_t type, void *mem)
{
#ifdef LWIP_HOOK_MEMP_AVAILABLE
  struct memp *old_first;
#endif
  RAW_OS_ERROR ret;

  RAW_MESSAGE_ERROR("memp_free: type < MEMP_MAX", (type < MEMP_MAX), return;);

  ret = raw_mutex_get(&memp_mutex_lock, RAW_WAIT_FOREVER);
  RAW_ASSERT(ret == RAW_SUCCESS);

#if MEMP_OVERFLOW_CHECK >= 2
  memp_overflow_check_all();
#endif /* MEMP_OVERFLOW_CHECK >= 2 */

#ifdef LWIP_HOOK_MEMP_AVAILABLE
  do_memp_free_pool(memp_pools[type], mem, &old_first);
#else
  do_memp_free_pool(memp_pools[type], mem);
#endif

 
  ret = raw_mutex_put(&memp_mutex_lock);
  RAW_ASSERT(ret == RAW_SUCCESS);
  
#ifdef LWIP_HOOK_MEMP_AVAILABLE
  if (old_first == 0) {
    LWIP_HOOK_MEMP_AVAILABLE(type);
  }
#endif
}


